$("#mfilepic").fileinput({
    showPreview: true,
    showUpload: true,
    append: false,
    uploadLabel: "上传", removeLabel: "移除", language: "zh",
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/file?type=Goods&f=pic',
    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
}).on("fileuploaded", function (event, data) {
    console.log(data);
    $("#hidpic").val(data.response.data);
})

$("#mfileskupic").fileinput({
    showPreview: true,
    showUpload: true,
    uploadLabel: "上传", removeLabel: "移除", language: "zh",
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/file?type=Goods&f=skupic',
    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
}).on("fileuploaded", function (event, data) {
    console.log(data);
    $("#hidskupic").val(data.response.data);
})

var sortphotos, sortphotos2;

$("#mfilephotos").fileinput({
    showPreview: false,
    showUpload: true,
    uploadLabel: "上传", removeLabel: "移除", language: "zh",
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/file?type=Goods&f=photos',
    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
}).on("fileuploaded", function (event, data) {
    console.log('--------fileuploaded');
    console.log(data);
    $("#hidphotos").val($("#hidphotos").val().length == 0 ? data.response.data : $("#hidphotos").val() + ";" + data.response.data);
    sortphotos = createsort('photos')
}).on("filebatchuploadsuccess", function (event, data, previewId, index) {
    console.log('--------filebatchuploadsuccess');
    console.log(data);
    $("#hidphotos").val($("#hidphotos").val().length == 0 ? data.response.data : $("#hidphotos").val() + ";" + data.response.data);
    sortphotos = createsort('photos')
}).on('filedeleted', function (event, key, jqXHR, data) {
    console.log('--------filedeleted');
    console.log(key);
    $("#hidphotos").val(filedeleted($("#hidphotos").val(), key));
    sortphotos = createsort('photos')
})

var sortinfo, sortinfo2;
$("#mfileinfo").fileinput({
    showPreview: false,
    showUpload: true,
    uploadLabel: "上传", removeLabel: "移除", language: "zh",
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/file?type=Goods&f=info',
    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
}).on("fileuploaded", function (event, data) {
    $("#hidinfo").val($("#hidinfo").val().length == 0 ? data.response.data : $("#hidinfo").val() + ";" + data.response.data);
    sortinfo = createsort('info')
}).on("filebatchuploadsuccess", function (event, data, previewId, index) {
    $("#hidinfo").val($("#hidinfo").val().length == 0 ? data.response.data : $("#hidinfo").val() + ";" + data.response.data);
    sortinfo = createsort('info')
}).on('filedeleted', function (event, key, jqXHR, data) {
    $("#hidinfo").val(filedeleted($("#hidinfo").val(), key));
    sortinfo = createsort('info')
})

$("#mfilehomeurl").fileinput({
    showPreview: true,
    showUpload: true,
    uploadLabel: "上传", removeLabel: "移除", language: "zh",
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/file?type=Goods&f=homeurl',
    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
}).on("fileuploaded", function (event, data) {
    console.log(data);
    console.log("---------------hidinfo.val()=" + $("#hidhomeurl").val());
    $("#hidhomeurl").val(data.response.data);
})

$("#mfileshareimg").fileinput({
    showPreview: true,
    showUpload: true,
    uploadLabel: "上传", removeLabel: "移除", language: "zh",
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/file?type=Goods&f=shareimg',
    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
}).on("fileuploaded", function (event, data) {
    console.log(data);
    console.log("---------------hidinfo.val()=" + $("#hidshareimg").val());
    $("#hidshareimg").val(data.response.data);
})

$('#dateStart').datepicker(dateformat);
$('#dateEnd').datepicker(dateformat);

function shareBonusTypeFormatter(value, row, index) {
    if (value == undefined || value == "") return "";
    else if (value == 0)
        return "无奖励";
    else if (value == 1)
        return "送积分";
    else if (value == 2)
        return "送现金";
    else if (value == 3)
        return "送优惠券";
    else return ""
}

function gtypeFormatter(value, row, index) {
    if (value == undefined || value == "") return "";
    else if (value == 1)
        return "实物产品";
    else if (value == 2)
        return "虚拟产品";
    else if (value == 3)
        return "到店服务";
    else if (value == 4)
        return "上门服务";
    else return ""
}

function glFormatter(value, row, index) {
    if (value == undefined || value == "") return "未关联";
    else if (value > 0)
        return "已关联";
}

function typeFormatter(value, row, index) {
    if (value == undefined || value == "" || value != "-1") return "否";
    else
        return "是";
}

function typePFormatter(value, row, index) {
    if (value == undefined || value == "" || value != "1") return "否";
    else
        return "是";
}

function sidFormatter(value, row, index) {
    if (value == undefined || value == "" || value == "0") return "平台商品";
    else if (value > 0)
        return "店铺商品";
    else return ""
}

function hasSkuFormatter(value, row, index) {
    if (value == undefined || value == "") return "否";
    else if (value == 1)
        return "是";
    else return "否";
}

function sjFormatter(value, row, index) {
    if (value == undefined || value == "") return "已下架";
    else if (value == 1)
        return "已上架";
    else return "已下架";
}

function spFormatter(value, row, index) {
    if (value == undefined || value == "") return "未关联";
    else if (value == 1)
        return "已关联";
    else return "未关联";
}

function sidFormatter(value, row, index) {
    if (value == undefined || value == "" || value == "0") return "平台";
    else return "商家";
}

function displayFL(gid, gdcid) {
    console.log("===========gid=" + gid)
    console.log("===========gdcid=" + gdcid)
    $("#hidgid").val(gid)
    $('#gdcid').find("option[value='" + gdcid + "']").attr("selected", true);

    $('#displayFL-form').modal("show");

    var gdcid = $("#gdcid").val()
    $.ajax({
        type: 'POST',
        url: "modify",
        data: {
            id: gid,
            gdcid: gdcid
        },
        success: function () {
            swal({title: "操作成功", text: "", type: "success"})
            $('#mytable').bootstrapTable('refresh');
        },
        dataType: "json"
    });
}

function savedisplayFL() {
    console.log("===================savedisplayFL")
    var gid = $("#hidgid").val()
    var gdcid = $("#gdcid").val()
    console.log("===================savedisplayFL gid=" + gid)
    console.log("===================savedisplayFL gdcid=" + gdcid)
    $.ajax({
        type: 'POST',
        url: "update",
        data: {
            id: gid,
            gdcid: gdcid
        },
        success: function (r) {
            console.log("=================savedisplayFL post ok")
            swal({title: "操作成功", text: "", type: "success"})
            $('#mytable').bootstrapTable('refresh');
            $('#displayFL-form').modal("hide");
            console.log("=================savedisplayFL post ok  444")
        },
        dataType: "json"
    });
}

function guanlianSJ(gid, gdcid) {
    console.log("===========gid=" + gid)
    console.log("===========gdcid=" + gdcid)
    $("#hidgid").val(gid)
    $("#hidgsid").val(gid)
    $('#guanlianSJ-form').modal("show");

    $('#gsmytable').bootstrapTable('refresh', {url: '/admin/goods/storelist'});
    initnonestore(gid)
}

//关联商品
function guanlianSP(gid, glgid) {
    console.log("===========gid=" + gid)
    console.log("===========glgid=" + glgid)
    $("#hidgid").val(gid)
    $("#hidglgid").val(glgid)
    $('#guanlianSP-form').modal("show");

    $('#glspmytable').bootstrapTable('refresh', {url: '/admin/goods/guanlianSPlist'});
}

//关联商品保存-单选
function guanlianSPSave(glgid) {
    var gid = $("#hidgid").val() || ''
    var glgid = glgid|| ''
    console.log("===========gid=" + gid)
    console.log("===========glgid=" + glgid)

    $.ajax({
        type: 'POST',
        url: "guanlianSP",
        data: {
            gid: gid,
            glgid: glgid
        },
        success: function (r) {
            console.log("=================guanlianSPSave post ok")
            swal({title: "操作成功", text: "", type: "success"})
            $('#glspmytable').bootstrapTable('refresh', {url: '/admin/goods/guanlianSPlist'});
            // $('#guanlianSP-form').modal("hide");
        },
        dataType: "json"
    });
}

function guanlianSJSave(sid, gid) {
    var gid = gid || $("#hidgsid").val()
    var sid = sid || $("#gsid").val()
    console.log("===========gid=" + gid)
    console.log("===========sid=" + sid)

    $.ajax({
        type: 'POST',
        url: "guanlianSJ",
        data: {
            gid: gid,
            sid: sid
        },
        success: function (r) {
            console.log("=================guanlianSJSave post ok")
            swal({title: "操作成功", text: "", type: "success"})
            $('#gsmytable').bootstrapTable('refresh', {url: '/admin/goods/storelist'});
            initnonestore(gid)
            $('#guanlianSJ-add-form').modal("hide");
        },
        dataType: "json"
    });
}

function guanlianSJSaveall(sid, gid) {
    var gid = $("#hidgsid").val()
    var sids = []
    var rows = $("#gstable").bootstrapTable('getSelections');// 获得要删除的数据
    if (rows.length == 0) {// rows 主要是为了判断是否选中，下面的else内容才是主要
        swal({title: "提示", text: "请先选择需要关联的商家", type: "error"})
        return;
    } else {
        $(rows).each(function () {// 通过获得别选中的来进行遍历
            sids.push(this.id);// cid为获得到的整条数据中的一列
        });
    }

    $.ajax({
        type: 'POST',
        url: "guanlianSJall",
        data: {
            gid: gid,
            sids: sids.join(";")
        },
        success: function (r) {
            console.log("=================guanlianSJSave post ok")
            swal({title: "操作成功", text: "", type: "success"})
            $('#gsmytable').bootstrapTable('refresh', {url: '/admin/goods/storelist'});
            initnonestore(gid)
            $('#guanlianSJ-add-form').modal("hide");
        },
        dataType: "json"
    });

}

//商品商家请求服务数据时所传参数
function gsqueryParams(params) {
    var p = {
        limit: params.limit,
        offset: params.offset,
        sort: params.sort,
        order: params.order,
        search: $('#gssearch').val(),
        gid: $('#hidgsid').val()
    }
    return p;
}

$('#gssearch_btn').click(function () {
    var p = {
        search: $('#gssearch').val(),
        ts: new Date().getTime()
    };
    $('#gstable').bootstrapTable('refresh', p);
})

function initnonestore(gid) {
    console.log("----------------initnonestore")
    console.log(gid)
    //生成用户数据
    var gstbparam = {
        method: 'get',
        url: "/admin/goods/getgstores?gid=" + gid,
        // height:520,//高度调整
        // toolbar: '#toolbar',
        striped: true, //是否显示行间隔色
        dataField: "records",
        pagination: true,//是否分页
        queryParamsType: 'limit',
        queryParams: gsqueryParams,
        sidePagination: 'server',
        pageNumber: 1, //初始化加载第一页，默认第一页
        pageSize: 30,//单页记录数
        pageList: [30, 100, 200, 500],//分页步进值
        showExport: true,//显示导出
        showRefresh: false,//刷新按钮
        showColumns: false,
        detailView: false,
        clikToSelect: true,//是否启用点击选中行
        // toolbarAlign:'right',
        // buttonsAlign:'right',//按钮对齐方式
        columns: [
            {
                title: '全选',
                field: 'select',
                checkbox: true,
                width: 25,
                align: 'center',
                valign: 'middle'
            },
            {
                title: 'ID',
                field: 'id',
                visible: false
            },
            {
                title: '商家名',
                field: 'name'
            }
            , {
                title: '操作',
                field: 'Attribute',
                align: 'center',
                width: 120,
                formatter: gsactFormatter
            }
        ],
        locale: 'zh-CN',//中文支持,
    }
    $('#gstable').bootstrapTable(gstbparam)
}

function saveguanlianSJ() {
    console.log("===================savedisplayFL")
    var gid = $("#hidgid").val()
    var gdcid = $("#gdcid").val()
    console.log("===================savedisplayFL gid=" + gid)
    console.log("===================savedisplayFL gdcid=" + gdcid)
    $.ajax({
        type: 'POST',
        url: "update",
        data: {
            id: gid,
            gdcid: gdcid
        },
        success: function (r) {
            console.log("=================savedisplayFL post ok")
            swal({title: "操作成功", text: "", type: "success"})
            $('#mytable').bootstrapTable('refresh');
            $('#displayFL-form').modal("hide");
            console.log("=================savedisplayFL post ok  444")
        },
        dataType: "json"
    });
}

function copyywid(id) {
    var tag = document.createElement('input');
    tag.setAttribute('id', 'cp_hgz_input');
    tag.value = id;
    document.getElementsByTagName('body')[0].appendChild(tag);
    document.getElementById('cp_hgz_input').select();
    document.execCommand('copy');
    document.getElementById('cp_hgz_input').remove();
    swal({title: '您已成功复制业务ID', text: '', timer: 2000})
}

function sjactFormatter(value, row, index) {
    var state = row.state;
    var id = row.id;
    var gdcid = row.gdcid;
    var isNav = row.isNav;
    var type = row.type;
    var gtype = row.gtype;
    var glgid = row.logisticsId||'';
    var id = row.id;
    var pic = row.pic;

    var res = '<button data-toggle="modal" class="btn-sm btn-primary" href="list.html#modal-form" data-row=' + id + ' data-index=' + index + '>修改</button>';
    res += '<button type="button" class="btn-sm btn-primary" onclick="clone(\'' + id + '\',-1)" >快速复制</button>';
    if ($('#isPintuan').val() == 1)
        res += ' <button type="button" class="btn-sm btn-danger" onclick="setpintuan(\'' + id + '\',\'' + index + '\')">设置拼团</button>';
    if (state == undefined) {
    } else if (state == 1)
        res += ' <button type="button" class="btn-sm btn-info" onclick="changeState(\'' + id + '\',-1)" >下架</button>';
    else
        res += ' <button typ-e="button" class="btn-sm btn-info" onclick="changeState(\'' + id + '\',1)" >上架</button>';
    res += ' <button typ-e="button" class="btn-sm btn-danger" onclick="deleteOne(\'' + id + '\')">删除</button>';
    if (isNav != 1 && $('#isAdmin').val() == 1)
        res += ' <button type="button" class="btn-sm btn-info" onclick="changeNavState(\'' + id + '\',1,\'' + pic + '\',\'' + id + '\')" >启用分类导航</button>';
    if (type != -1 && $('#isFenxiao').val() == 1) {
        res += ' <button type="button" class="btn-sm btn-info" onclick="setDailiSP(\'' + id + '\',\'' + index + '\')" >设置代理商品</button>';
        res += ' <button type="button" class="btn-sm btn-info" onclick="setFanli(\'' + id + '\',\'' + index + '\')" >设置商品返利</button>';
    }
    if (type == -5) {
        //神秘类型
        res += ' <button type="button" class="btn-sm btn-info" onclick="setLipinGuanlian(\'' + id + '\')" >礼品关联活动</button>';
    }
    res += ' <button type="button" class="btn-sm btn-info" onclick="displayFL(\'' + id + '\',\'' + gdcid + '\')" >设置显示分类</button>';
    res += ' <button type="button" class="btn-sm btn-info" onclick="copyywid(\'' + id + '\')" >复制业务ID</button>';

    if ($('#skusize').val() > 0)
        res += ' <button type="button" class="btn-sm btn-info" onclick="addSKU(\'' + id + '\',\'' + index + '\')" >添加规格</button>';
    var version = $('#hidversion').val();
    if (version == 4) res += ' <button typ-e="button" class="btn-sm btn-danger" onclick="guanlianSJ(\'' + id + '\',\'' + index + '\')">关联商家</button>';
    // if (version == 4) res += ' <button typ-e="button" class="btn-sm btn-danger" onclick="setQunzf(\'' + id + '\',\'' + index + '\')">设置群红包</button>';
    if (version == 4 && gtype == 3) res += ' <button typ-e="button" class="btn-sm btn-danger" onclick="guanlianSP(\'' + id + '\',\'' + glgid + '\')">套餐关联商品</button>';
    if (version == 6) res += ' <button typ-e="button" class="btn-sm btn-danger" onclick="setQunzf(\'' + id + '\',\'' + index + '\')">设置二级分佣</button>';

    return res;
}

function gsactFormatter(value, row, index) {
    var id = row.id;
    var gid = $("#hidgsid").val()
    var res = '<button type="button" class="btn-sm btn-info" onclick="guanlianSJSave(\'' + id + '\',\'' + gid + '\')" >关联</button>';
    return res;
}

function actgsFormatter(value, row, index) {
    var state = row.state;
    var id = row.id;
    var res = '';
    if (state == undefined) {
    } else if (state == 1)
        res += ' <button type="button" class="btn-sm btn-info" onclick="changegsState(\'' + id + '\',-1)" >禁用</button>';
    else
        res += ' <button typ-e="button" class="btn-sm btn-info" onclick="changegsState(\'' + id + '\',1)" >启用</button>';
    res += ' <button type="button" class="btn-sm btn-danger" onclick="gsdelete(\'' + id + '\')">删除</button>';
    return res;
}

function actglspFormatter(value, row, index) {
    var state = row.state;
    var id = row.id;
    var res = '';
    if (state != 1)
        res += ' <button type="button" class="btn-sm btn-info" onclick="guanlianSPSave(\'' + id + '\')" >关联</button>';
    else res += ' <button type="button" class="btn-sm btn-primary" >已关联</button>';
    return res;
}

function zgfanFormatter(value, row, index) {
    var state = row.state;
    var id = row.id;
    var res = !row.zgfanMount || row.zgfanMount == '' || row.zgfanMount == 0 ? "无奖励" : row.zgfanMount + (row.zgfanType == 1 ? "积分" : row.zgfanType == 2 ? "现金" : row.zgfanType == 3 ? "优惠券" : row.zgfanType == 4 ? "币" : "");
    return res;
}

function tjfanFormatter(value, row, index) {
    var state = row.state;
    var id = row.id;
    var res = !row.shareMount || row.shareMount == '' || row.shareMount == 0 ? "无奖励" : row.shareMount + (row.shareBonusType == 1 ? "积分" : row.shareBonusType == 2 ? "现金" : row.shareBonusType == 3 ? "优惠券" : row.shareBonusType == 4 ? "币" : "");
    return res;
}

var rows = []

function actsubFormatter(value, row, index) {
    var state = row.state;
    var id = row.id;
    console.log("===============================actsubFormatter")
    console.log("==========value=" + value)
    console.log("==========index=" + index)
    console.log(row)
    // var gdcid = row.gdcid;
    // var isNav = row.isNav;
    // var type = row.type;
    // var pic = row.pic;
    rows[id] = row
    // var res =' ';
    var res = ' <button type="button" class="btn-sm btn-info" onclick="modifySKU(\'' + id + '\',\'' + index + '\')" >修改</button>';

    if (state == undefined) {
    } else if (state == 1)
        res += ' <button type="button" class="btn-sm btn-info" onclick="changeSkuState(\'' + id + '\',-1)" >下架</button>';
    else
        res += ' <button typ-e="button" class="btn-sm btn-info" onclick="changeSkuState(\'' + id + '\',1)" >上架</button>';
    res += ' <button typ-e="button" class="btn-sm btn-danger" onclick="deleteSkuOne(\'' + id + '\')">删除</button>';

    // if (type != -1 &&$('#isFenxiao').val() == 1) {
    //     res += ' <button type="button" class="btn-sm btn-info" onclick="setDailiSP(\'' + id + '\',\'' + index + '\')" >设置代理商品</button>';
    //     res += ' <button type="button" class="btn-sm btn-info" onclick="setFanli(\'' + id + '\',\'' + index + '\')" >设置商品返利</button>';
    // }
    // res += ' <button type="button" class="btn-sm btn-info" onclick="displayFL(\'' + id + '\',\'' + gdcid + '\')" >设置显示分类</button>';
    return res;
}

function changeNavState(id, state, pic) {
    console.log(">>>>>>>changeNavState and pic=" + pic)
    if (!pic || pic.length == 0) {
        swal({title: "设置分类导航前需上传分类图标", text: "", type: "warning"})
        return
    }
    $.ajax({
        type: 'POST',
        url: "changeNavState",
        data: {
            id: id,
            pic: pic,
            state: state
        },
        success: function () {
            swal({title: "操作成功", text: "", type: "success"})
            $('#mytable').bootstrapTable('refresh', {url: '/admin/goods/list'});
        },
        dataType: "json"
    });
}

function changeState(id, state) {
    $.ajax({
        type: 'POST',
        url: "changeState",
        data: {
            id: id,
            state: state
        },
        success: function () {
            $('#mytable').bootstrapTable('refresh', {url: '/admin/goods/list'});
        },
        dataType: "json"
    });
}

function clone(id) {
    $.ajax({
        type: 'POST',
        url: "clone",
        data: {
            id: id
        },
        success: function () {
            $('#mytable').bootstrapTable('refresh', {url: '/admin/goods/list'});
        },
        dataType: "json"
    });
}

function changeSkuState(id, state) {
    $.ajax({
        type: 'POST',
        url: "changeSkuState",
        data: {
            id: id,
            state: state
        },
        success: function () {
            $('#mytable').bootstrapTable('refresh', {url: '/admin/goods/list'});
        },
        dataType: "json"
    });
}

function changegsState(id, state) {
    $.ajax({
        type: 'POST',
        url: "changegsState",
        data: {
            id: id,
            state: state
        },
        success: function () {
            $('#mytable').bootstrapTable('refresh', {url: '/admin/goods/storelist'});
        },
        dataType: "json"
    });
}

function deleteOne(id) {
    swal({
        title: '您确定要删除此行数据？',
        text: '你将无法恢复它！',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#ed5666',
        confirmButtonText: '确定删除！',
        cancelButtonText: '取消删除！',
        confirmButtonClass: 'btn btn-success',
        cancelButtonClass: 'btn btn-danger',
        buttonsStyling: false
    }).then(function () {
        $.ajax({
            type: 'POST',
            url: "deleteOne",
            data: {
                id: id,
            },
            success: function (status) {
                if (status == 1) {
                    swal({title: "删除成功", text: "", type: "success"})
                    $('#mytable').bootstrapTable('refresh', {url: '/admin/goods/list'});
                } else {
                    swal({title: "删除失败", text: "", type: "error"})
                }
            },
            dataType: "json"
        });

    }, function (dismiss) {
        // dismiss的值可以是'cancel', 'overlay',
        // 'close', 'timer'
        if (dismiss === 'cancel') {
            swal({title: '您已取消操作！', text: '', timer: 2000})
        }
    })
}

function deleteSkuOne(id) {
    swal({
        title: '您确定要删除此行数据？',
        text: '你将无法恢复它！',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#ed5666',
        confirmButtonText: '确定删除！',
        cancelButtonText: '取消删除！',
        confirmButtonClass: 'btn btn-success',
        cancelButtonClass: 'btn btn-danger',
        buttonsStyling: false
    }).then(function () {
        $.ajax({
            type: 'POST',
            url: "deleteSkuOne",
            data: {
                id: id,
            },
            success: function (status) {
                if (status == 1) {
                    swal({title: "删除成功", text: "", type: "success"})
                    $('#mytable').bootstrapTable('refresh', {url: '/admin/goods/list'});
                } else {
                    swal({title: "删除失败", text: "", type: "error"})
                }
            },
            dataType: "json"
        });

    }, function (dismiss) {
        // dismiss的值可以是'cancel', 'overlay',
        // 'close', 'timer'
        if (dismiss === 'cancel') {
            swal({title: '您已取消操作！', text: '', timer: 2000})
        }
    })
}

function gsdelete(id) {
    swal({
        title: '您确定要删除此行数据？',
        text: '你将无法恢复它！',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#ed5666',
        confirmButtonText: '确定删除！',
        cancelButtonText: '取消删除！',
        confirmButtonClass: 'btn btn-success',
        cancelButtonClass: 'btn btn-danger',
        buttonsStyling: false
    }).then(function () {
        $.ajax({
            type: 'POST',
            url: "gsdelete",
            data: {
                id: id,
            },
            success: function (status) {
                if (status == 1) {
                    swal({title: "删除成功", text: "", type: "success"})
                    $('#gsmytable').bootstrapTable('refresh', {url: '/admin/goods/storelist'});
                } else {
                    swal({title: "删除失败", text: "", type: "error"})
                }
            },
            dataType: "json"
        });

    }, function (dismiss) {
        // dismiss的值可以是'cancel', 'overlay',
        // 'close', 'timer'
        if (dismiss === 'cancel') {
            swal({title: '您已取消操作！', text: '', timer: 2000})
        }
    })
}

var editsw = [];

//设置拼团
function setpintuan(id, index) {
    var data = $('#mytable').bootstrapTable("getData")[index]
    console.log("======setpintuan")
    console.log(data)
    console.log(data)
    $('#hidpgid').val(data.id)
    $('#ptname').val(data.name);
    $('#ptotal').val(data.ptotal);
    $('#ptprice').val(data.price);

    $('#ptsaleprice').val(data.saleprice);
    $('#ptdateStart').val(data.dateStart);
    $('#ptdateEnd').val(data.dateEnd);

    $('#modal-pintuan-form').modal();
}

//设置代理
function setDailiSP(id, index) {
    var data = $('#mytable').bootstrapTable("getData")[index]
    console.log("======setDailiSP")
    console.log(data)
    $('#fxgid').val(data.id);
    $('#dlname').val(data.name);
    $('#dlprice').val(data.saleprice);
    $('#modal-daili-form').modal();
    $('#hidhuifei').val($("#huifei option:selected").val());
}

//设置礼品关联活动
function setLipinGuanlian(id, index) {
    console.log("===id=" + sid)
    swal({
        title: "设置神秘礼品关联活动",
        text: "",
        type: "info",
        input: "text",
        showCancelButton: true,
        closeOnConfirm: false,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        animation: "slide-from-top",
        inputPlaceholder: "填写活动业务ID"
    }).then(function (res) {
        if (res.length == 0) {
            swal("请填写填写活动业务ID");
            return
        }
        $.ajax({
            type: 'POST',
            url: "guanlianLinpin",
            data: {
                id: id,
                ywid: res,
            },
            success: function (e) {
                if (e.code == 0) {
                    swal({title: "操作成功", text: e.info, type: "success"})
                    $('#mytable').bootstrapTable('refresh', {url: '/admin/goods/list'});
                } else {
                    swal({title: "操作失败", text: e.msg, type: "error"})
                }
            },
            dataType: "json"
        });
    }, function (dismiss) {
        // dismiss的值可以是'cancel', 'overlay',
        // 'close', 'timer'
        if (dismiss === 'cancel') {
            swal({title: '您已取消操作！', text: '', timer: 2000})
        }
    })
}

//添加SKU子商品
function addSKU(id, index) {
    var data = $('#mytable').bootstrapTable("getData")[index]
    console.log("============addSKU")
    console.log(data)
    $('#skuagid').val(data.id);
    $('#skuapic').val(data.pic);
    $('#askuname').val(data.name);
    $('#askusaleprice').val(data.saleprice);
    $('#askucharacteristic').val(data.characteristic);
    $('#modal-sku-add-form').modal();
    // $('#hidhuifei').val($("#huifei option:selected").val());
}

//添加SKU子商品
function modifySKU(id, index) {
    // var data = $('#subtable').bootstrapTable("getData")[index]
    var data = rows[id]
    console.log("======modifySKU")
    console.log(data)

    $('#skuid').val(data.id);
    $('#hidmext1').val(data.ext1);
    $('#hidmext2').val(data.ext2);
    $('#hidmext3').val(data.ext3);
    $('#hidmext4').val(data.ext4);
    $('#hidmext5').val(data.ext5);
    $('#hidmextids').val(data.extids);

    $('#skuname').val(data.name);
    $('#skuprice').val(data.price);
    $('#skusaleprice').val(data.saleprice);
    $('#skustores').val(data.stores);//库存
    $('#skucharacteristic').val(data.characteristic);

    // $('#cid').find("option[value='" + data['cid'] + "']").attr("selected", true);
    $("#mfileskupic2").fileinput('destroy');
    $("#mfileskupic2").fileinput({
        showPreview: true,
        showUpload: true,
        append: true, overwriteInitial: false,
        uploadClass: "btn btn-info",
        uploadLabel: "上传", removeLabel: "移除", language: "zh",
        uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> ",
        initialPreviewShowDelete: true,
        initialPreviewAsData: true,
        initialPreviewFileType: 'image',
        initialPreview: getPreviewList(data.pic),
        previewFileIcon: '<i class="fa fa-file"></i>',
        allowedPreviewTypes: ['image'],
        initialPreviewConfig: getPreviewConfig(data.pic, 'GoodsSku', "pic", data.id),
        elErrorContainer: '#kartik-file-errors',
        uploadUrl: '/admin/upload/file?type=Goods&f=pic',
        allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
    }).on("fileuploaded", function (event, data) {
        console.log(data);
        $("#hidskupic2").val(data.response.data);
    }).on('filedeleted', function (event, key, jqXHR, data) {
        console.log('filedeleted Key = ' + key);
        $("#hidskupic2").val("");
    })
    $('#hidskupic2').val(data.pic);

    $('#modal-sku-form').modal();

    // 初始化规格
    var extids = []
    extids = data.extids.split("_");
    if (extids.length == 0) return;
    var idx = []
    for (var i = 0; i < extids.length; i++) {
        var ggid = "#mskutype" + (i + 1);
        var skuid = "#msku" + (i + 1);
        $(ggid).empty();
        $(skuid).empty();
        if (i > 0) $(ggid).append("<option value=''>请选择</option>");
        idx[extids[i]] = i + 1
        $.ajax({
            //请求方式
            type: "POST",
            //请求地址
            url: "skucfgitem",
            //数据，json字符串
            data: {"id": extids[i]},
            //请求成功
            success: function (res) {
                console.log("===========================ajax result");
                console.log(res);
                var gggid = "#mskutype" + idx[res.data.cid]
                var skuuid = "#msku" + idx[res.data.cid]
                $.each(res.data.plist, function (index, item) {
                    $(gggid).append("<option value=" + item.id + ">" + item.name + "</option>");
                });
                $(gggid).find("option[value='" + res.data.pid + "']").attr("selected", true);

                $.each(res.data.childs, function (index, item) {
                    $(skuuid).append("<option value=" + item.id + ">" + item.name + "</option>");
                });
                $(skuuid).find("option[value='" + res.data.cid + "']").attr("selected", true);
            },
            //请求失败，包含具体的错误信息
            error: function (e) {
                console.log(e.status);
                console.log(e.responseText);
            }
        });
    }

    // $('#fxgid').val(data.id);
    // $('#hidhuifei').val($("#huifei option:selected").val());
}

function setFanli(id, index) {
    var data = $('#mytable').bootstrapTable("getData")[index]
    console.log("======setFanli")
    console.log(data)
    $('#fanligid').val(data.id);

    $('#goodsName').val(data.name);
    $('#saleprice').val(data.saleprice);

    $('#zgfanMount').val(data.zgfanMount);
    $('#shareMount').val(data.shareMount);

    $('#fantimeType').find("option[value='" + data['fantimeType'] + "']").attr("selected", true);
    $('#fxmode').find("option[value='" + data['fxmode'] + "']").attr("selected", true);

    $('#zgfanType').find("option[value='" + data['zgfanType'] + "']").attr("selected", true);
    if (data['zgfanYwid'] && data['zgfanYwid'] > 0)
        $('#zgfanYwid').find("option[value='" + data['zgfanYwid'] + "']").attr("selected", true);

    $('#shareBonusType').find("option[value='" + data['shareBonusType'] + "']").attr("selected", true);
    if (data['shareYwid'] && data['shareYwid'] > 0)
        $('#shareYwid').find("option[value='" + data['shareYwid'] + "']").attr("selected", true);

    if (data['zgfanType'] == 3) $('#zgfanquan').show()
    else $('#zgfanquan').hide()

    if (data['shareBonusType'] == 3) $('#sharefanquan').show()
    else $('#sharefanquan').hide()

    $.ajax({
        //请求方式
        type: "get",
        //请求地址
        url: "getGoodsFanli",
        //数据，json字符串
        data: {"gid": data.id},
        //请求成功
        success: function (res) {
            if (res.code == 0) {
                var d=res.data
                $('#zgfanMount').val(d.zgfanMount);
                $('#zgfanYwid').val(d.zgfanYwid);
                $('#shareMount').val(d.shareMount);
                $('#fanli1').val(d.fanli1);
                $('#fanli2').val(d.fanli2);

                $('#zgfanType').find("option[value='" + d['zgfanType'] + "']").attr("selected", true);
                $('#shareBonusType').find("option[value='" + d['shareBonusType'] + "']").attr("selected", true);
                $('#shareYwid').find("option[value='" + d['shareYwid'] + "']").attr("selected", true);
                $('#fantimeType').find("option[value='" + d['fantimeType'] + "']").attr("selected", true);
                $('#fxmode').find("option[value='" + d['fxmode'] + "']").attr("selected", true);

                $('#modal-fanli-form').modal("show");
            }
        },
        //请求失败，包含具体的错误信息
        error: function (e) {
            $('#modal-fanli-form').modal("show");
        }
    });
}

function setQunzf(id, index) {
    var data = $('#mytable').bootstrapTable("getData")[index]
    console.log("============setQunzf")
    console.log(data)
    $('#qunzfgid').val(data.id);
    console.log("============$('#qunzfgid').val()" + $('#qunzfgid').val())

    $.ajax({
        //请求方式
        type: "get",
        //请求地址
        url: "getQunzf",
        //数据，json字符串
        data: {"gid": data.id},
        //请求成功
        success: function (res) {
            console.log("===========================ajax result");
            console.log(res);
            if (res.code == 0) {
                var d=res.data
                $('#jiangMount').val(d.jiangMount);
                $('#jiangFenshu').val(d.jiangFenshu);
                $('#minDianji').val(d.minDianji);
                $('#oneptimes').val(d.oneptimes);

                $('#jiangType').find("option[value='" + d['jiangType'] + "']").attr("selected", true);
                $('#jiangState').find("option[value='" + d['state'] + "']").attr("selected", true);

                $('#modal-qunzf-form').modal("show");
            }
        },
        //请求失败，包含具体的错误信息
        error: function (e) {
            console.log(e.status);
            console.log(e.responseText);
            $('#modal-qunzf-form').modal("show");
        }
    });


    $('#modal-qunzf-form').modal();
}

function afxlevelChange(level) {
    //可以根据自己页面情况进行调整
    var level = level
    console.log(level)
    $("#huifei").find("option[value = '" + level + "']").attr("selected", "selected");
    $('#hidhuifei').val($("#huifei option:selected").val());
    console.log($("#huifei option:selected").val())
}

function zgfanTypeChange(level) {
    //可以根据自己页面情况进行调整
    var level = level
    console.log(level)
    if (level == "3")
        $('#zgfanquan').show();
    else
        $('#zgfanquan').hide();
}

function shareBonusTypeChange(level) {
    //可以根据自己页面情况进行调整
    var level = level
    console.log(level)
    if (level == "3")
        $('#sharefanquan').show();
    else
        $('#sharefanquan').hide();
}
function shareFxmodeChange(level) {
    //可以根据自己页面情况进行调整
    var level = level
    console.log(level)
    if (level == "1")
        $('#fanliSetting').show();
    else{
        $('#fanliSetting').hide();
        $('#fanli1').val('');
        $('#fanli2').val('');
    }
}

/**
 * 为模态框填充数据
 */
$('#modal-form').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget); // 触发事件的按钮
    var index = button.data('index');
    var modal = $(this);
    var data = $('#mytable').bootstrapTable("getData")[index]
    console.log(data)
    if (!data) return;
    modal.find('#id').val(data.id)
    modal.find('#characteristic').val(data.characteristic)
    modal.find('#logisticsId').val(data.logisticsId)
    modal.find('#minPrice').val(data.minPrice)
    modal.find('#price').val(data.price)
    modal.find('#saleprice').val(data.saleprice)

    modal.find('#name').val(data.name)
    modal.find('#goodsNo').val(data.goodsNo)
    modal.find('#numberFav').val(data.numberFav)
    modal.find('#numberGrade').val(data.numberGrade)
    modal.find('#numberOrders').val(data.numberOrders)
    modal.find('#numberSale').val(data.numberSale)

    modal.find('#paixu').val(data.paixu)
    modal.find('#dateStart').val(data.dateStart)
    modal.find('#dateEnd').val(data.dateEnd)
    modal.find('#propertyIds').val(data.propertyIds)
    modal.find('#recommend').val(data.recommend)

    modal.find('#jifen').val(data.jifen)
    modal.find('#stores').val(data.stores)
    modal.find('#jieshao').val(data.jieshao)
    modal.find('#xiangou').val(data.xiangou)
    modal.find('#videoId').val(data.videoId)
    modal.find('#sharewa').val(data.sharewa)

    // 此部分需要注意：如果页面有两个以上的图片编辑
    // 该部分逻辑需要重写
    modal.find('#maxUseCoupon').val(data.maxUseCoupon)
    modal.find('#shareMount').val(data.shareMount)
    modal.find('#barcode').val(data.barcode)
    modal.find('#weight').val(data.weight)
    modal.find('#views').val(data.views)
    modal.find('#userId').val(data.userId)

    editsw["isMember"] == undefined ? editsw["isMember"] = new Switchery(document.querySelector('#isMember'), {color: "#1AB394"}) : ""
    if (data.isMember == 1) {
        setSwitchery(editsw["isMember"], true);
    } else {
        setSwitchery(editsw["isMember"], false);
    }
    editsw["isJifen"] == undefined ? editsw["isJifen"] = new Switchery(document.querySelector('#isJifen'), {color: "#1AB394"}) : ""
    if (data.isJifen == 1) {
        setSwitchery(editsw["isJifen"], true);
    } else {
        setSwitchery(editsw["isJifen"], false);
    }
    editsw["isCoupon"] == undefined ? editsw["isCoupon"] = new Switchery(document.querySelector('#isCoupon'), {color: "#1AB394"}) : ""
    if (data.isCoupon == 1) {
        setSwitchery(editsw["isCoupon"], true);
    } else {
        setSwitchery(editsw["isCoupon"], false);
    }
    editsw["isRecommend"] == undefined ? editsw["isRecommend"] = new Switchery(document.querySelector('#isRecommend'), {color: "#1AB394"}) : ""
    if (data.isRecommend == 1) {
        setSwitchery(editsw["isRecommend"], true);
    } else {
        setSwitchery(editsw["isRecommend"], false);
    }
    editsw["isHot"] == undefined ? editsw["isHot"] = new Switchery(document.querySelector('#isHot'), {color: "#1AB394"}) : ""
    if (data.isHot == 1) {
        setSwitchery(editsw["isHot"], true);
    } else {
        setSwitchery(editsw["isHot"], false);
    }

    $("#mfilepic2").fileinput('destroy');
    $("#mfilepic2").fileinput({
        showPreview: true,
        showUpload: true,
        append: false,
        overwriteInitial: false,
        uploadClass: "btn btn-info",
        uploadLabel: "上传", removeLabel: "移除", language: "zh",
        uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> ",
        initialPreviewShowDelete: true,
        initialPreviewAsData: true,
        initialPreviewFileType: 'image',
        initialPreview: getPreviewList(data.pic),
        previewFileIcon: '<i class="fa fa-file"></i>',
        allowedPreviewTypes: ['image'],
        initialPreviewConfig: getPreviewConfig(data.pic, 'Goods', "pic", data.id),
        elErrorContainer: '#kartik-file-errors',
        uploadUrl: '/admin/upload/file?type=Goods&f=pic',
        allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
    }).on("fileuploaded", function (event, data) {
        console.log(data);
        console.log("---------hidpic2.val=" + $("#hidpic2").val());
        $("#hidpic2").val(data.response.data);
    }).on('filedeleted', function (event, key, jqXHR, data) {
        console.log('Key = ' + key);
        $("#hidpic2").val('');
    })
    $("#hidpic2").val(data.pic)

    $("#mfilephotos2").fileinput('destroy');
    $("#mfilephotos2").fileinput({
        showPreview: false,
        showUpload: true,
        append: true,
        uploadAsync: true,
        overwriteInitial: false,
        uploadClass: "btn btn-info",
        uploadLabel: "上传", removeLabel: "移除", language: "zh",
        uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> ",
        initialPreviewShowDelete: true,
        initialPreviewAsData: true,
        initialPreviewFileType: 'image',
        initialPreview: getPreviewList(data.photos),
        previewFileIcon: '<i class="fa fa-file"></i>',
        allowedPreviewTypes: ['image'],
        initialPreviewConfig: getPreviewConfig(data.photos, 'Goods', "photos", data.id),
        elErrorContainer: '#kartik-file-errors',
        uploadUrl: '/admin/upload/file?type=Goods&f=photos',
        allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
    }).on("fileuploaded", function (event, data) {
        console.log(data);
        console.log("---------hidpic2.val=" + $("#hidphotos2").val());
        $("#hidphotos2").val($("#hidphotos2").val().length == 0 ? data.response.data : $("#hidphotos2").val() + ";" + data.response.data);
        sortphotos2 = createsort('photos2')
    }).on("filebatchuploadsuccess", function (event, data, previewId, index) {
        $("#hidphotos2").val($("#hidphotos2").val().length == 0 ? data.response.data : $("#hidphotos2").val() + ";" + data.response.data);
        sortphotos2 = createsort('photos2')
    }).on('filedeleted', function (event, key, jqXHR, data) {
        console.log('Key = ' + key);
        console.log('$("#hidphotos2").val() = ' + $("#hidphotos2").val());
        $("#hidphotos2").val(filedeletedbak($("#hidphotos2").val(), $("#hidphotos2bak").val(), key));
        console.log('$("#hidphotos2").val() = ' + $("#hidphotos2").val());
        sortphotos2 = createsort('photos2')
    })

    $("#hidphotos2").val(data.photos)
    $("#hidphotos2bak").val(data.photos)
    sortphotos2 = createsort('photos2')

    $("#mfileinfo2").fileinput('destroy');
    $("#mfileinfo2").fileinput({
        showPreview: false,
        showUpload: true,
        append: true,
        uploadAsync: false,
        overwriteInitial: false,
        uploadClass: "btn btn-info",
        uploadLabel: "上传", removeLabel: "移除", language: "zh",
        uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> ",
        initialPreviewShowDelete: true,
        initialPreviewAsData: true,
        initialPreviewFileType: 'image',
        initialPreview: getPreviewList(data.info),
        previewFileIcon: '<i class="fa fa-file"></i>',
        allowedPreviewTypes: ['image'],
        initialPreviewConfig: getPreviewConfig(data.info, 'Goods', "info", data.id),
        elErrorContainer: '#kartik-file-errors',
        uploadUrl: '/admin/upload/file?type=Goods&f=info',
        allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
    }).on("fileuploaded", function (event, data) {
        $("#hidinfo2").val($("#hidinfo2").val().length == 0 ? data.response.data : $("#hidinfo2").val() + ";" + data.response.data);
        sortinfo2 = createsort('info2')
    }).on("filebatchuploadsuccess", function (event, data, previewId, index) {
        $("#hidinfo2").val($("#hidinfo2").val().length == 0 ? data.response.data : $("#hidinfo2").val() + ";" + data.response.data);
        sortinfo2 = createsort('info2')
    }).on('filedeleted', function (event, key, jqXHR, data) {
        $("#hidinfo2").val(filedeletedbak($("#hidinfo2").val(), $("#hidinfo2bak").val(), key));
        sortinfo2 = createsort('info2')
    })
    $("#hidinfo2").val(data.info)
    $("#hidinfo2bak").val(data.info)
    sortinfo2 = createsort('info2')

    // $("#mfilepackinglist2").fileinput('destroy');
    // $("#mfilepackinglist2").fileinput({
    //     showPreview: true,
    //     showUpload: true,
    //     append: true,overwriteInitial:false,
    //     uploadClass: "btn btn-info",
    //     uploadLabel: "上传",removeLabel: "移除",language: "zh",
    //     uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> ",
    //     initialPreviewShowDelete: true,
    //     initialPreviewAsData: true,
    //     initialPreviewFileType: 'image',
    //     initialPreview: getPreviewList(data.packinglist),
    //     previewFileIcon: '<i class="fa fa-file"></i>',
    //     allowedPreviewTypes: ['image'],
    //     initialPreviewConfig: getPreviewConfig(data.packinglist, 'goods', "packinglist", data.id),
    //     elErrorContainer: '#kartik-file-errors',
    //     uploadUrl: '/admin/upload/file?type=Goods',
    //     allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
    // }).on("fileuploaded", function (event, data) {
    //     console.log(data);
    //     $("#hidpackinglist2").val($("#hidpackinglist2").val().length==0?data.response.data:$("#hidpackinglist2").val()+ ";" + data.response.data);
    // }).on('filedeleted', function(event, key, jqXHR, data) {
    //     console.log('filedeleted Key = ' + key);
    //     $("#hidpackinglist2").val(filedeleted($("#hidpackinglist2").val(),key));
    // })
    // $("#hidpackinglist2").val(data.packinglist)
    //
    // $("#mfileafterservice2").fileinput('destroy');
    // $("#mfileafterservice2").fileinput({
    //     showPreview: true,
    //     showUpload: true,
    //     append: true,overwriteInitial:false,
    //     uploadClass: "btn btn-info",
    //     uploadLabel: "上传",removeLabel: "移除",language: "zh",
    //     uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> ",
    //     initialPreviewShowDelete: true,
    //     initialPreviewAsData: true,
    //     initialPreviewFileType: 'image',
    //     initialPreview: getPreviewList(data.afterservice),
    //     previewFileIcon: '<i class="fa fa-file"></i>',
    //     allowedPreviewTypes: ['image'],
    //     initialPreviewConfig: getPreviewConfig(data.afterservice, 'goods', "afterservice", data.id),
    //     elErrorContainer: '#kartik-file-errors',
    //     uploadUrl: '/admin/upload/file?type=Goods',
    //     allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
    // }).on("fileuploaded", function (event, data) {
    //     console.log(data);
    //     $("#hidafterservice2").val($("#hidafterservice2").val().length==0?data.response.data:$("#hidafterservice2").val()+ ";" + data.response.data);
    // }).on('filedeleted', function(event, key, jqXHR, data) {
    //     console.log('filedeleted Key = ' + key);
    //     $("#hidafterservice2").val(filedeleted($("#hidafterservice2").val(),key));
    // })
    // $("#hidafterservice2").val(data.afterservice)
    //
    // $("#mfileintroduction2").fileinput('destroy');
    // $("#mfileintroduction2").fileinput({
    //     showPreview: true,
    //     showUpload: true,
    //     append: true,overwriteInitial:false,
    //     uploadClass: "btn btn-info",
    //     uploadLabel: "上传",removeLabel: "移除",language: "zh",
    //     uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> ",
    //     initialPreviewShowDelete: true,
    //     initialPreviewAsData: true,
    //     initialPreviewFileType: 'image',
    //     initialPreview: getPreviewList(data.introduction),
    //     previewFileIcon: '<i class="fa fa-file"></i>',
    //     allowedPreviewTypes: ['image'],
    //     initialPreviewConfig: getPreviewConfig(data.introduction, 'goods', "introduction", data.id),
    //     elErrorContainer: '#kartik-file-errors',
    //     uploadUrl: '/admin/upload/file?type=Goods',
    //     allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
    // }).on("fileuploaded", function (event, data) {
    //     console.log(data);
    //     $("#hidintroduction2").val($("#hidintroduction2").val().length==0?data.response.data:$("#hidintroduction2").val()+ ";" + data.response.data);
    // }).on('filedeleted', function(event, key, jqXHR, data) {
    //     console.log('filedeleted Key = ' + key);
    //     $("#hidintroduction2").val(filedeleted($("#hidintroduction2").val(),key));
    // })
    // $("#hidintroduction2").val(data.introduction)

    $("#mfilehomeurl2").fileinput('destroy');
    $("#mfilehomeurl2").fileinput({
        showPreview: true,
        showUpload: true,
        append: false,
        overwriteInitial: false,
        uploadClass: "btn btn-info",
        uploadLabel: "上传", removeLabel: "移除", language: "zh",
        uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> ",
        initialPreviewShowDelete: true,
        initialPreviewAsData: true,
        initialPreviewFileType: 'image',
        initialPreview: getPreviewList(data.homeurl),
        previewFileIcon: '<i class="fa fa-file"></i>',
        allowedPreviewTypes: ['image'],
        initialPreviewConfig: getPreviewConfig(data.homeurl, 'Goods', "homeurl", data.id),
        elErrorContainer: '#kartik-file-errors',
        uploadUrl: '/admin/upload/file?type=Goods&f=homeurl',
        allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
    }).on("fileuploaded", function (event, data) {
        console.log(data);
        $("#hidhomeurl2").val(data.response.data);
    }).on('filedeleted', function (event, key, jqXHR, data) {
        console.log('filedeleted Key = ' + key);
        $("#hidhomeurl2").val('');
    })
    $("#hidhomeurl2").val(data.homeurl)

    $("#mfileshareimg2").fileinput('destroy');
    $("#mfileshareimg2").fileinput({
        showPreview: true,
        showUpload: true,
        append: false,
        overwriteInitial: false,
        uploadClass: "btn btn-info",
        uploadLabel: "上传", removeLabel: "移除", language: "zh",
        uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> ",
        initialPreviewShowDelete: true,
        initialPreviewAsData: true,
        initialPreviewFileType: 'image',
        initialPreview: getPreviewList(data.shareimg),
        previewFileIcon: '<i class="fa fa-file"></i>',
        allowedPreviewTypes: ['image'],
        initialPreviewConfig: getPreviewConfig(data.shareimg, 'Goods', "shareimg", data.id),
        elErrorContainer: '#kartik-file-errors',
        uploadUrl: '/admin/upload/file?type=Goods&f=shareimg',
        allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
    }).on("fileuploaded", function (event, data) {
        console.log(data);
        $("#hidshareimg2").val(data.response.data);
    }).on('filedeleted', function (event, key, jqXHR, data) {
        console.log('filedeleted Key = ' + key);
        $("#hidshareimg2").val('');
    })
    $("#hidshareimg2").val(data.shareimg)

    modal.find('#cid').find("option[value='" + data['cid'] + "']").attr("selected", true);
    modal.find('#type').find("option[value='" + data['type'] + "']").attr("selected", true);
    modal.find('#gtype').find("option[value='" + data['gtype'] + "']").attr("selected", true);
    modal.find('#maxUseJifen').find("option[value='" + data['maxUseJifen'] + "']").attr("selected", true);
    modal.find('#shareBonusType').find("option[value='" + data['shareBonusType'] + "']").attr("selected", true);
})


/**
 * 为SKU模态框填充数据
 */
$('#modal-sku-form').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget); // 触发事件的按钮
    var index = button.data('index');
    var modal = $(this);
    var data = $('#mytable').bootstrapTable("getData")[index]
    console.log(data)
    if (!data) return;
    modal.find('#skuid').val(data.id)
    modal.find('#name').val(data.name)
    modal.find('#saleprice').val(data.saleprice)
    modal.find('#characteristic').val(data.characteristic)

    $("#mskumfile").fileinput('destroy');
    $("#mskumfile").fileinput({
        showPreview: true,
        showUpload: true,
        append: true, overwriteInitial: false,
        uploadClass: "btn btn-info",
        uploadLabel: "上传", removeLabel: "移除", language: "zh",
        uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> ",
        initialPreviewShowDelete: true,
        initialPreviewAsData: true,
        initialPreviewFileType: 'image',
        initialPreview: getPreviewList(data.photos),
        previewFileIcon: '<i class="fa fa-file"></i>',
        allowedPreviewTypes: ['image'],
        initialPreviewConfig: getPreviewConfig(data.photos, 'Goods', "photos", data.id),
        elErrorContainer: '#kartik-file-errors',
        uploadUrl: '/admin/upload/file?type=Goods&f=photos',
        allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
    }).on("fileuploaded", function (event, data) {
        console.log('fileuploaded data = ' + data);
        $("#skumphotos").val($("#skumphotos").val() + ";" + data.response.data);
    }).on('filedeleted', function (event, key, jqXHR, data) {
        console.log('filedeleted Key = ' + key);
        $("#skumphotos").val(filedeleted($("#skumphotos").val(), key));
        console.log("--------after delete hidphotos2.val=" + data);
    })
    $("#skumphotos").val(data.photos)

    modal.find('#cid').find("option[value='" + data['cid'] + "']").attr("selected", true);
    modal.find('#type').find("option[value='" + data['type'] + "']").attr("selected", true);
    modal.find('#gtype').find("option[value='" + data['gtype'] + "']").attr("selected", true);
    modal.find('#maxUseJifen').find("option[value='" + data['maxUseJifen'] + "']").attr("selected", true);
    modal.find('#shareBonusType').find("option[value='" + data['shareBonusType'] + "']").attr("selected", true);
})

//tableHeight函数
function tableHeight() {
    //可以根据自己页面情况进行调整
    return $(window).height() - 200;
}

$(function () {

    var sw = [];
    $(".js-switch").each(function (i, e) {
        sw[i] = new Switchery(e, {color: "#1AB394"})
    })
    $(window).resize(function () {
        $('#mytable').bootstrapTable('resetView', {
            height: tableHeight()
        })
    })

    //生成用户数据
    var tbparam = {
        method: 'get',
        url: "/admin/goods/list",
        // height:520,//高度调整
        // toolbar: '#toolbar',
        striped: true, //是否显示行间隔色
        dataField: "records",
        pagination: true,//是否分页
        queryParamsType: 'limit',
        queryParams: queryParams,
        sidePagination: 'server',
        pageNumber: 1, //初始化加载第一页，默认第一页
        pageSize: 20,//单页记录数
        pageList: [20, 100, 200, 500],//分页步进值
        showExport: true,//显示导出
        showRefresh: false,//刷新按钮
        showColumns: false,
        clikToSelect: true,//是否启用点击选中行
        // toolbarAlign:'right',
        // buttonsAlign:'right',//按钮对齐方式
        columns: [
            {
                title: '全选',
                field: 'select',
                checkbox: true,
                width: 25,
                align: 'center',
                valign: 'middle'
            },
            {
                title: 'ID',
                field: 'id',
                visible: false
            },
            {
                title: '商品名',
                field: 'name'
            },
            // {
            //     title: '商品编号',
            //     field: 'goodsNo'
            // },
            {
                title: '商品原价',
                field: 'price'
            },
            {
                title: '实际售价',
                field: 'saleprice'
            },
            {
                title: '成本价',
                field: 'minPrice'
            },
            {
                title: '订单数',
                field: 'numberOrders'
            },
            {
                title: '销量数',
                field: 'numberSale'
            },
            {
                title: '总库存数',
                field: 'stores'
            },
            {
                title: '商品主图',
                field: 'pic',
                formatter: "imgFormatter"
            },
            {
                title: '自购奖励',
                field: 'zgfanMount',
                formatter: "zgfanFormatter"
            },
            {
                title: '推荐奖励',
                field: 'shareMount',
                formatter: "tjfanFormatter"
            },
            // {
            //     title: '支持会员卡',
            //     field: 'isMember',
            //     formatter: "sfFormatter"
            // },
            // {
            //     title: '支持积分',
            //     field: 'isJifen',
            //     formatter: "sfFormatter"
            // },
            // {
            //     title: '支持优惠券',
            //     field: 'isCoupon',
            //     formatter: "sfFormatter"
            // },
            // {
            //     title: '是否热推',
            //     field: 'isRecommend',
            //     formatter: "sfFormatter"
            // },
            // {
            //     title: '是否sku',
            //     field: 'hasSku',
            //     formatter: "hasSkuFormatter"
            // },
            // {
            //     title: '是否拼团',
            //     field: 'type',
            //     formatter: "typePFormatter"
            // },
            {
                title: '产品类型',
                field: 'gtype',
                formatter: "gtypeFormatter"
            },
            // {
            //     title: '商品类型',
            //     field: 'sid',
            //     formatter: "sidFormatter"
            // },
            // {
            //     title: '是否分销',
            //     field: 'type',
            //     formatter: "typeFormatter"
            // },
            {
                title: '平台|商家',
                field: 'sid',
                formatter: "sidFormatter"
            },
            {
                title: '上架状态',
                field: 'state',
                formatter: "sjFormatter"
            },
            {
                title: '操作',
                field: 'Attribute',
                align: 'center',
                width: 360,
                formatter: sjactFormatter
            }
        ],
        locale: 'zh-CN',//中文支持,
    }

    if ($('#skusize').val() > 0) {
        console.log("-------$('#skusize').val()=" + $('#skusize').val())
        tbparam.detailView = true,//父子表
            tbparam.onExpandRow = function (index, row, $detail) {
                initSubTable(index, row, $detail);
            }
    }
    $('#mytable').bootstrapTable(tbparam)

    //生成用户数据
    var gstbparam = {
        method: 'get',
        url: "/admin/goods/storelist",
        // height:520,//高度调整
        // toolbar: '#toolbar',
        striped: true, //是否显示行间隔色
        dataField: "records",
        pagination: true,//是否分页
        queryParamsType: 'limit',
        queryParams: gsqueryParams,
        sidePagination: 'server',
        pageNumber: 1, //初始化加载第一页，默认第一页
        pageSize: 50,//单页记录数
        pageList: [50],//分页步进值
        showExport: true,//显示导出
        showRefresh: false,//刷新按钮
        showColumns: false,
        clikToSelect: true,//是否启用点击选中行
        // toolbarAlign:'right',
        // buttonsAlign:'right',//按钮对齐方式
        columns: [
            {
                title: '全选',
                field: 'select',
                checkbox: true,
                width: 25,
                align: 'center',
                valign: 'middle'
            },
            {
                title: 'ID',
                field: 'id',
                visible: false
            },
            {
                title: '商品名',
                field: 'gname'
            },
            {
                title: '店铺名称',
                field: 'sname'
            },
            {
                title: '启用状态',
                field: 'state',
                formatter: "sjFormatter"
            },
            {
                title: '操作',
                field: 'Attribute',
                align: 'center',
                width: 240,
                formatter: actgsFormatter
            }
        ],
        locale: 'zh-CN',//中文支持,
    }

    $('#gsmytable').bootstrapTable(gstbparam)

    //服务套餐关联商品数据
    var glsptbparam = {
        method: 'get',
        url: "/admin/goods/guanlianSPlist",
        // height:520,//高度调整
        // toolbar: '#toolbar',
        striped: true, //是否显示行间隔色
        dataField: "records",
        pagination: true,//是否分页
        queryParamsType: 'limit',
        queryParams: glspqueryParams,
        sidePagination: 'server',
        pageNumber: 1, //初始化加载第一页，默认第一页
        pageSize: 50,//单页记录数
        pageList: [50],//分页步进值
        showExport: true,//显示导出
        showRefresh: false,//刷新按钮
        showColumns: false,
        clikToSelect: true,//是否启用点击选中行
        // toolbarAlign:'right',
        // buttonsAlign:'right',//按钮对齐方式
        columns: [
            {
                title: 'ID',
                field: 'id',
                visible: false
            },
            {
                title: '商品名',
                field: 'name'
            },
            {
                title: '是否关联',
                field: 'state',
                formatter: "spFormatter"
            },
            {
                title: '操作',
                field: 'Attribute',
                align: 'center',
                width: 240,
                formatter: actglspFormatter
            }
        ],
        locale: 'zh-CN',//中文支持,
    }

    $('#glspmytable').bootstrapTable(glsptbparam)

    //请求服务数据时所传参数
    function initSubTable(index, row, $detail) {
        console.log(index)
        console.log(row)
        console.log($detail)
        $("hidsid2").val(row.id)
        var gid = row.id;
        console.log("======gid=" + gid)

        var cur_table = $detail.html('<table></table>').find('table');
        $(cur_table).bootstrapTable({
            url: "/admin/goods/skulist",
            method: 'get',
            queryParams: {gid: gid, offset: 0, limit: 50},
            // ajaxOptions: {sid: sid},
            clickToSelect: true,
            detailView: false,//父子表
            uniqueId: "id",
            dataField: "records",
            queryParamsType: 'limit',
            locale: 'zh-CN',//中文支持,
            sidePagination: 'server',
            pagination: false,//是否分页
            columns: [{
                checkbox: false
            }, {
                title: 'ID',
                field: 'id',
                visible: false
            },
                {
                    title: '商品名称',
                    field: 'name'
                },
                {
                    title: '单价',
                    field: 'saleprice'
                },
                {
                    title: '规格1',
                    field: 'ext1'
                },
                {
                    title: '规格2',
                    field: 'ext2'
                },
                {
                    title: '规格3',
                    field: 'ext3'
                },
                {
                    title: '规格4',
                    field: 'ext4'
                },
                {
                    title: '规格5',
                    field: 'ext5'
                },
                {
                    title: '规格',
                    field: 'extids',
                    visible: false
                },
                // {
                //     title: '总库存数',
                //     field: 'stores'
                // },
                {
                    title: '上架状态',
                    field: 'state',
                    formatter: "sjFormatter"
                },
                {
                    title: '操作',
                    field: 'Attribute',
                    align: 'center',
                    width: 260,
                    formatter: actsubFormatter
                }
            ]
        })
    }

    //请求服务数据时所传参数
    function queryParams(params) {
        var p = {
            limit: params.limit,
            offset: params.offset,
            sort: params.sort,
            order: params.order
            , search: $('#search').val()
            , type: $('#qtype').val()
            , state: $('#qstate').val()
            , gcategory: $('#gcategory').val()
        }
        return p;
    }

    //商品商家请求服务数据时所传参数
    function gsqueryParams(params) {
        var p = {
            limit: params.limit,
            offset: params.offset,
            sort: params.sort,
            order: params.order
            , gid: $('#hidgid').val()
        }
        return p;
    }

    //商品商家请求服务数据时所传参数
    function glspqueryParams(params) {
        var p = {
            limit: params.limit,
            offset: params.offset,
            sort: params.sort,
            order: params.order
            , gid: $('#hidgid').val()
        }
        return p;
    }

    $('#search_btn').click(function () {
        var p = {
            status: $('#qstatus').val(),
            state: $('#qstate').val(),
            search: $('#search').val(),
            ts: new Date().getTime()
        };
        $('#mytable').bootstrapTable('refresh', p);
    })

    /*
     * 验证错误提示信息高亮
     */
    $.validator.setDefaults({
        highlight: function (e) {
            $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
        }, success: function (e) {
            e.closest(".form-group").removeClass("has-error").addClass("has-success")
        }, errorElement: "span", errorPlacement: function (e, r) {
            e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
        }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
    }), $("#aform").validate(), $("#mform").validate();
})

function checkAdd() {
    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("name") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("name") + "=" + $(this).val())
        }
    });
    var xg = $("#xiangou2").val();

    if (xg == "无") {
        $("#xiangou2").val(0)
    }
    if (!$.num(xg, true)) {
        return;
    }

    if ($("#hidphotos").attr("required") == "required"
        && $("#hidphotos").val() == "") {
        swal({title: "请上传图片", text: "", type: "warning"})
        return false;
    }

    console.log($('#info').val())
    return true;
}

function checkskuAdd() {
    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("name") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("name") + "=" + $(this).val())
        }
    });
    var xg = $("#xiangou2").val();

    if (xg == "无") {
        $("#xiangou2").val(0)
    }
    if (!$.num(xg, true)) {
        return;
    }

    if ($("#hidphotos").attr("required") == "required"
        && $("#hidphotos").val() == "") {
        swal({title: "请上传图片", text: "", type: "warning"})
        return false;
    }

    console.log($('#info').val())
    return true;
}

function checkModify() {

    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("id") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("id") + "=" + $(this).val())
        }
    });


    // if ($("#hidpic2").attr("required") == "required"
    //     && $("#hidpic2").val() == "") {
    //     swal({title: "请上传图片", text: "", type: "warning"})
    //     return false;
    // }

    return true;
}

function checkskuModify() {

    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("id") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("id") + "=" + $(this).val())
        }
    });


    // if ($("#hidpic2").attr("required") == "required"
    //     && $("#hidpic2").val() == "") {
    //     swal({title: "请上传图片", text: "", type: "warning"})
    //     return false;
    // }

    return true;
}

function pintuan() {

    if ($("#dateStart").val() > $("#dateEnd").val()) {
        swal({title: "提示", text: "拼团开始日期不能大于结束日期", type: "warning"})
        return false;
    }

    return true;
}

function fanli() {

    // if ($("#dateStart").val() > $("#dateEnd").val()) {
    //     swal({title: "提示", text: "拼团开始日期不能大于结束日期", type: "warning"})
    //     return false;
    // }

    return true;
}

function skutypeChange(val, skytype, idx, type) {
    console.log("===========================val=" + val);
    $("#" + skytype).empty();
    if (val == "") {

    } else {
        $("#" + skytype).append("<option value=''>请选择</option>");
        $.ajax({
            //请求方式
            type: "POST",
            //请求地址
            url: "skucfg",
            //数据，json字符串
            data: {"pid": val},
            //请求成功
            success: function (res) {
                console.log("===========================ajax result");
                console.log(res);
                $.each(res.data, function (index, item) {
                    $("#" + skytype).append("<option value=" + item.id + ">" + item.name + "</option>");
                });
            },
            //请求失败，包含具体的错误信息
            error: function (e) {
                console.log(e.status);
                console.log(e.responseText);
            }
        });
    }
}

function skuChange(val, idx, type) {
    console.log("===========================val=" + val);
    console.log("===========================type=" + type);
    //重新计算 extids
    var extids = ""

    if (type == "a") {
        for (var m = 1; m < 6; m++) {
            if ($("#asku" + m).val() != "") {
                extids += "_" + $("#asku" + m).val()
                $("#hidaext" + m).val($("#asku" + m).find("option:selected").text())
                console.log("#hidaext" + m + "=" + $("#hidaext" + m).val())
            }
        }
        extids = extids.substring(1).replace(/_null/g, "");
        $("#hidaextids").val(extids)
        console.log("=======hidaextids=" + $("#hidaextids").val())
    } else {
        for (var m = 1; m < 6; m++) {
            if ($("#msku" + m).val() != "") {
                extids += "_" + $("#msku" + m).val()
                $("#hidmext" + m).val($("#msku" + m).find("option:selected").text())
            }
        }
        extids = extids.substring(1).replace(/_null/g, "")
        $("#hidmextids").val(extids)
        console.log("=======hidmextids=" + $("#hidmextids").val())

    }
}